package com.jdy.haoduoai.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.HabitPlan;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.CustomTimeDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;
import java.util.HashMap;

import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

//import com.jdy.haoduoai.R;


@SuppressLint("InflateParams")
public class BabyHabitAdapter extends BaseAdapter {

  private BaseActivity mContext;
  private ArrayList<HabitPlan> mList;
  private LayoutInflater mInflter;
  DisplayImageOptions options;

  private SparseArray<View> cvArray = new SparseArray<>();

  public interface OnSetAlarmListener2 {
    void finishSetAlarm2();
  }

  private OnSetAlarmListener2 mOnSetAlarmListener;

  public void setOnSetAlarmListener(OnSetAlarmListener2 mmOnSetAlarmListener) {
    this.mOnSetAlarmListener = mmOnSetAlarmListener;
  }

  private CustomTimeDialog timeDlg;

  private void setHabitTime(final HabitPlan iitem) {
    CustomTimeDialog.Builder customBuilder = new CustomTimeDialog.Builder(
            mContext);
    customBuilder.setTitle("设置每次启动时间")
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("确定", new CustomTimeDialog.Builder.OnOkClickListener() {
      @Override
      public void onClickOk(final int hourOfDay, final int minute) {
        timeDlg.dismiss();

        Async.start(new Func0<ResponseResult>() {
          @Override
          public ResponseResult call() {
            LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
            if (lu == null) {
              lu = Tools.restoreLeUser();
            }

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, lu.sno);
            param_.put("time", String.format("%02d", hourOfDay) + ":"
                    + String.format("%02d", minute));

            return HttpUtils.startRequest(HttpUtils.API_URL
                            + "/api/2.0/operation/teacher/habit/update_habits/" + iitem.id, param_,
                    HttpUtils.TAG_POST_REQUEST);
          }
        }).filter(new Func1<ResponseResult, Boolean>() {
          @Override
          public Boolean call(ResponseResult arg0) {
            return arg0 != null && Tools.isNotEmpty(arg0)
                    && arg0.isSuccess();
          }
        }).doOnCompleted(new Action0() {
          @Override
          public void call() {
            // TODO
          }
        }).subscribe(new Action1<ResponseResult>() {
          @Override
          public void call(ResponseResult result) {
            if (mOnSetAlarmListener != null && result.isSuccess()) {
              mOnSetAlarmListener.finishSetAlarm2();
            }
          }
        });

      }
    });

    if (!mContext.isFinishing()) {
      timeDlg = customBuilder.create();
      timeDlg.show();
    }
  }

  public BabyHabitAdapter(BaseActivity context,
                          ArrayList<HabitPlan> list) {
    this.mContext = context;
    this.mList = list;
    mInflter = LayoutInflater.from(mContext);
    // this.mType = type;

    options = new DisplayImageOptions.Builder()
            .showImageOnFail(R.drawable.default_img_listitem) // 下载 失败 显示的 图片
            .cacheInMemory(true) // 缓存
            .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
            .build();

    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
            mContext).writeDebugLogs().build();
    ImageLoader.getInstance().init(configuration);
  }

  @Override
  public int getCount() {
    return mList.size();
  }

  @Override
  public Object getItem(int position) {
    return mList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  public interface OnConfirmClassListener {
    public void OnConfirmClick(int pos);
  }

  public void setData (ArrayList<HabitPlan> list ) {
    mList = list;
    notifyDataSetChanged();
  }

  public OnConfirmClassListener getConfirmClassListener() {
    return mOnConfirmClassListener;
  }

  public void setConfirmClassListener(OnConfirmClassListener mOnConfirmClassListener) {
    this.mOnConfirmClassListener = mOnConfirmClassListener;
  }

  private  OnConfirmClassListener mOnConfirmClassListener;

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
    final HabitPlan itemVo = mList.get(position);
    ViewHolder holder;

    convertView = cvArray.get(position);

    if (convertView == null) {
      holder = new ViewHolder();
      convertView = mInflter.inflate(R.layout.babyhabit_item, null);
//      holder.iv_channelicon = (ImageView) convertView
//          .findViewById(R.id.iv_channelicon);
      holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title22);
      holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
      holder.img_gou = (ImageView) convertView.findViewById(R.id.img_gou);
      holder.lin_push = convertView.findViewById(R.id.lin_push);
      holder.img_push  = (ImageView) convertView.findViewById(R.id.img_push);
      //  holder.rel_root22 = convertView.findViewById(R.id.rel_root22);
      convertView.setTag(holder);
      cvArray.put(position, convertView);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    holder.lin_push.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        new CustomAsyncTask(mContext, new IAsyncTask() {
          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {
            if (result.isSuccess()) {
              Toast.makeText(mContext, "已推送到设备播放", Toast.LENGTH_SHORT).show();
            } else {
              if (Tools.isNotNullStr(result.data)) {
                Toast.makeText(mContext, result.data, Toast.LENGTH_SHORT).show();
              }
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            HashMap<String, Object> param_ = new HashMap<String, Object>();

            LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
            if (lu == null) {
              lu = Tools.restoreLeUser();
            }
            param_.put(HttpUtils.TAG_SNO_I, lu.sno);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
            param_.put(HttpUtils.TAG_ACTION_I, "play");
          //  param_.put("mode", "im");
            param_.put(HttpUtils.TAG_OPERATION_I, "teacher_habit");
            param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(itemVo.id));
            param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

            return HttpUtils.startRequest(HttpUtils.API_URL
                            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
                    HttpUtils.TAG_GET_REQUEST);

          }
        }).execute();
      }
    });

    holder.img_push.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    holder.img_push.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        new CustomAsyncTask(mContext, new IAsyncTask() {
          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {
            if (result.isSuccess()) {
              Toast.makeText(mContext, "已推送到设备播放", Toast.LENGTH_SHORT).show();
            } else {
              if (Tools.isNotNullStr(result.data)) {
                Toast.makeText(mContext, result.data, Toast.LENGTH_SHORT).show();
              }
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            HashMap<String, Object> param_ = new HashMap<String, Object>();
            LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
            if (lu == null) {
              lu = Tools.restoreLeUser();
            }
            param_.put(HttpUtils.TAG_SNO_I, lu.sno);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
            param_.put(HttpUtils.TAG_ACTION_I, "play");
          //  param_.put("mode", "im");
            param_.put(HttpUtils.TAG_OPERATION_I, "teacher_habit");
            param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(itemVo.id));
            param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

            return HttpUtils.startRequest(HttpUtils.API_URL
                            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
                    HttpUtils.TAG_GET_REQUEST);
          }
        }).execute();
      }
    });

    holder.img_gou.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        new CustomAsyncTask(mContext, new IAsyncTask() {

          @Override
          public void onRecieveData(Activity activity, final ResponseResult result) {

            if (result.isSuccess()) {
//              mResultTestMain = JsonSerializer.getInstance().deserialize(
//                      result.data, ResultTestMain.class);
              if (mOnConfirmClassListener!=null) {
                itemVo.checked = 1;
                mOnConfirmClassListener.OnConfirmClick(position);
                //  notifyDataSetChanged();
              }
            } else {
              //toastShow(result.data);
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
            if (lu == null) {
              lu = Tools.restoreLeUser();
            }

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, lu.sno);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
            // param_.put("id", itemVo.id);

            return HttpUtils.startRequest(HttpUtils.API_URL
                            + "/api/2.0/operation/teacher/habit/finish_habits/" + itemVo.id, param_,
                    HttpUtils.TAG_POST_REQUEST);
          }
        }).execute();
      }
    });

    holder.tv_title.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        setHabitTime(itemVo);
      }
    });

    if (Tools.isNotEmpty(itemVo)) {
      holder.tv_time.setText(itemVo.name);
      holder.tv_title.setText(itemVo.time.substring(0,5));
      //   holder.tv_time.setText(itemVo.time.substring(0,5));

      if (itemVo.checked == 1) {
        Drawable db2 = mContext.getResources().getDrawable(
                R.drawable.green_circle_icon);
        holder.tv_title.setCompoundDrawablesWithIntrinsicBounds(db2,
                null, null, null);
        holder.img_gou.setImageResource(R.drawable.green_gou);
        holder.img_gou.setClickable(false);
      } else {
        Drawable db2 = mContext.getResources().getDrawable(
                R.drawable.blue_circle_icon);
        holder.tv_title.setCompoundDrawablesWithIntrinsicBounds(db2,
                null, null, null);
        holder.img_gou.setImageResource(R.drawable.gray_gou);
      }
    }




//    String label = mList.get(position).date;
//    if (position == 0//检查列表项起始字母是否发生了改变，如果发生改变，该列表项就是分段中的第一项，修改分段标头的内容并显示该分段标头,否则隐藏
//            || !mList.get(position - 1).date.equalsIgnoreCase(label)) {
//      holder.text1.setVisibility(View.VISIBLE);
//
////      holder.text1.setText(Tools.getWeek(label) + " " + label.substring(0,4)
////              + "年" + label.substring(5,7) + "月" + label.substring(8,label.length()) + "日");
//    } else {
//      holder.text1.setVisibility(View.GONE);//隐藏分段标头
//    }

//    if (itemVo.checked == 1) {
//                  Drawable db2 = mContext.getResources().getDrawable(
//                R.drawable.green_circle_icon);
//      holder.tv_title.setCompoundDrawablesWithIntrinsicBounds(db2,
//                null, null, null);
//  //    holder.tv_time.setImageResource(R.drawable.red_flower);
//    } else {
//      Drawable db2 = mContext.getResources().getDrawable(
//              R.drawable.blue_circle_icon);
//      holder.tv_title.setCompoundDrawablesWithIntrinsicBounds(db2,
//              null, null, null);
//    //  holder.tv_time.setImageResource(R.drawable.gray_fllower);
//    }


//    holder.rel_root22.setOnLongClickListener(new View.OnLongClickListener() {
//      @Override
//      public boolean onLongClick(View v) {
//        showPopMenu(v);
//        return true;
//      }
//    });

//    if (Tools.isNotEmpty(itemVo)) {
//      if (Tools.isNotEmpty(itemVo.catalog)) {
//        if (itemVo.catalog.contains("cartoon")
//            || itemVo.catalog.contains("radio")) {
//          holder.tv_title.setText(itemVo.album_name);
//        } else {
//          holder.tv_title.setText(itemVo.name);
//        }
//      } else {
//        holder.tv_title.setText(itemVo.album_name);
//      }
//
//      ImageLoader.getInstance().displayImage(itemVo.cover,
//          holder.iv_channelicon, options);
    //  }

    return convertView;
  }

  private static class ViewHolder {
    private TextView tv_title, tv_time;
    private ImageView img_gou;
    private View lin_push;
    private ImageView img_push;
    //   private View rel_root22;
    //  private ImageView iv_channelicon;

  }

}
